package cn.seaboot.admin.video;

import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;

/**
 * 分段资源
 *
 * IO 复制过程中，只复制其中一部分
 * <p>
 * 前端开发过程中，使用 video 标签时，需要视频支持分段写出，
 */
public class PartialResource extends AbstractResource {
    private final Resource resource;
    private final long start;
    private final long end;

    /**
     * 分段资源，区间左闭右开
     *
     * @param resource 资源
     * @param start    起始 byte
     * @param end      结束 byte
     */
    public PartialResource(Resource resource, long start, long end) {
        this.resource = resource;
        this.start = start;
        this.end = end;
    }

    @NotNull
    @Override
    public InputStream getInputStream() throws IOException {
        InputStream inputStream = resource.getInputStream();
        // 跳过 n 字节
        long skipped = inputStream.skip(start);
        if (skipped < start) {
            // 如果输入流不支持 skip（如某些网络流），需要手动读取丢弃
            while (skipped < start) {
                long remaining = start - skipped;
                byte[] discardBuf = new byte[(int) Math.min(4096, remaining)];
                int n = inputStream.read(discardBuf);
                if (n == -1) break;
                skipped += n;
            }
        }
        return new PartialInputStream(inputStream, end - start + 1);
    }

    @Override
    public long contentLength() {
        return end - start + 1;
    }

    @NotNull
    @Override
    public String getDescription() {
        return "Partial content of " + resource.getDescription();
    }
}